// let {execute} = require('../db/utils');
// ctx koa的上下文实例
// ctx.db.insert/update/delete/select

let jwt = require('jsonwebtoken');

let getList = async ctx => {
  let {userid} = ctx.query;
  let sql = 'select * from user';
  let res = await ctx.db.execute(sql);
  ctx.body = {
    code: -1,
    user: res
  };
};


let getUser = async ctx => {
  let {userid} = ctx.query;
  // 根据userid查找对应的人
  // 如果没有穿userid就查找所有人

  let sql = `select * from user`;
  sql = userid ? sql += ` where userid=${userid}` : sql;
  ctx.body = await ctx.db.execute(sql);
};

let login = async ctx => {
  let {username, password} = ctx.request.body;
  // 根据userid查找对应的人
  // 如果没有穿userid就查找所有人

  let sql = `select * from zt_user`;
  sql += ` where name='${username}' AND password='${password}'`;
  console.log(sql);
  let res = await ctx.db.execute(sql);
  if (res.length === 0) {
    ctx.body = {
      code: -1,
      msg: '登录失败,用户名或者密码错误'
    };
  } else {

    let token = jwt.sign({username, password}, ctx.key, {
      expiresIn: '30d' // 30天  30y  20年  30h 30小时
    });

    ctx.body = {
      code: 1,
      token,
      name: res[0].name,
      avtor: res[0].avtor,
      router_id: res[0].router_id,
      user_id: res[0].user_id
    };
  }
};

let userInfo = async ctx => {
  let {name} = ctx.query;
  // 根据userid查找对应的人
  // 如果没有穿userid就查找所有人

  let sql = `select * from zt_user`;
  sql += ` where name='${name}'`;
  let res = await ctx.db.execute(sql);
  if (res.length === 0) {
    ctx.status = 401;
    ctx.body = {
      code: -1,
      msg: '获取用户信息失败'
    };
  } else {
    ctx.body = {
      code: 1,
      name: res[0].name,
      router_id: res[0].router_id,
    };
  }
};

module.exports = {
  getList, getUser,login,userInfo
};
